package edu.uow.devdocs

import grails.converters.JSON
import edu.uow.devdocs.Project
import edu.uow.devdocs.DevelopmentTask

class DevelopmentTaskController {
    static scaffold = true
	def currentUserService
	def statusService
	def assignmentService
	def developmentTaskService
	def issueService
	def emailService
	
	def ajaxGetDevelopmentTasks(Integer id, String update) {
		def list = DevelopmentTask.findAllByIssue(Issue.get(id))
		def result = ['id':update, 'data':
		list.collect() {
			[
				id:it.id,
				description:it.task
			]
		}]
		render result as JSON
	}
	
	def list() {
		params.max = Math.min(params.max ? params.int('max') : 25, 100)
		render(view:'list',
			model:[developmentTaskInstanceList: DevelopmentTask.list(params), 
				developmentTaskInstanceTotal: DevelopmentTask.count(),
				userProjects:currentUserService.currentUser.projects])
	}
	
	def resolve() {
		statusService.resolveCascadeDevelopmentTask(DevelopmentTask.get(params?.id))
		redirect(action:'edit', 'id': params?.id)
	}
	
	def quickTask() {
		def projectList = currentUserService.currentUser.projects
		println Project.allProjectsForPerson(currentUserService.currentUserId).list()
		render(view:'quickTask', 
			model:[
				quickTaskInstance: new QuickTaskCommand(),
				projectList: Project.allProjectsForPerson(currentUserService.currentUserId).list(),
				deploymentList: Deployment.active.list()])
	}
	
	def saveQuickTask(QuickTaskCommand quickTaskInstance) {
		if (quickTaskInstance.validate()) {
			def issue = issueService.createDefaultIssue(quickTaskInstance?.description, quickTaskInstance?.project, quickTaskInstance?.issueType)
			def developmentTask = developmentTaskService.createDefaultDevelopmentTask(quickTaskInstance?.description, issue, quickTaskInstance?.project, quickTaskInstance?.deployment)
			if (quickTaskInstance?.person) {
				def assignment = assignmentService.createDefaultAssignment(developmentTask, quickTaskInstance.project, quickTaskInstance.person)
				emailService.notifyNewAssignment(assignment)
				flash.message = message(code: 'quicktask.created.and.assigned', args: [issue?.id, developmentTask?.id, assignment?.id])
				
			} else {
			flash.message = message(code: 'quicktask.created', args: [issue?.id, task?.id])
			}
			render(view:'edit',model:[developmentTaskInstance:developmentTask])
		} else {
			def projectList = currentUserService.currentUser.projects
			render(view:'quickTask', 
				model:[
					quickTaskInstance: quickTaskInstance,
					projectList: Project.allProjectsForPerson(currentUserService.currentUserId).list(),
					deploymentList: Deployment.active.list()])
		}

	}
}

class QuickTaskCommand {
	String description
	IssueType issueType
	Project project
	Deployment deployment
	Person person
	
	static constraints = {
		description(blank:false, size: 3..255)
		issueType()
		project()
		deployment(nullable: true)
		person(nullable: true)
	}
}
